package convert.converter;

import com.opencsv.CSVReader;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.opencsv.exceptions.CsvException;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class csv_to_json {

    public static void main(String[] args) {
        String csvFilePath = "src/resource/csv/input.csv";
        String jsonFilePath = "src/resource/json/output1.json";

        convertCSVToJson(csvFilePath, jsonFilePath);
    }

    public static void convertCSVToJson(String csvFilePath, String jsonFilePath) {
        try {
            CSVReader csvReader = new CSVReader(new FileReader(csvFilePath));
            List<String[]> rows = csvReader.readAll();
            csvReader.close();

            String[] headers = rows.get(0);
            List<Map<String, String>> dataList = new ArrayList<>();

            for (int i = 1; i < rows.size(); i++) {
                String[] rowData = rows.get(i);
                Map<String, String> dataMap = createDataMap(headers, rowData);
                dataList.add(dataMap);
            }

            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 启用美化输出
            ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); // 使用默认的美化格式
            FileWriter fileWriter = new FileWriter(jsonFilePath);
            writer.writeValue(fileWriter, dataList);
            fileWriter.close();

            System.out.println("CSV to JSON conversion completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CsvException e) {
            throw new RuntimeException(e);
        }
    }

    private static Map<String, String> createDataMap(String[] headers, String[] rowData) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            String value = rowData[i];
            dataMap.put(header, value);
        }
        return dataMap;
    }
}

